package com.minisoft.rxjava;
import io.reactivex.rxjava3.core.Observable;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class CreaterOperatorDemo {

    /**
     *演示defer延迟创建操作符
     */
    @Test
    public void deferDemo()
    {
        AtomicInteger foo = new AtomicInteger(100);
        Observable observable = Observable.just(foo.get());
        /**
         *延迟创建
         */
        Observable dObservable = Observable.defer(
                () -> Observable.just(foo.get()));

        /**
         *修改对象的值
         */
        foo.set(200);
        /**
         *有观察者订阅
         */
        observable.subscribe(
                integer -> log.info("just emit {}", String.valueOf(integer)));
        /**
         *有观察者订阅
         */
        dObservable.subscribe(
                integer -> log.info("defer just emit {}", String.valueOf(integer)));

    }

    /**
     *演示interval转换
     */
    @Test
    public void intervalDemo() throws InterruptedException
    {
        Observable
                .interval(100, TimeUnit.MILLISECONDS)
                .subscribe(aLong -> log.info(aLong.toString()));

        Thread.sleep(Integer.MAX_VALUE);
    }

    /**演示 range的基本使用 */
    @Test
    public void rangeDemo() {
        //逐一发一组范围内的整数序列
        Observable.range(1, 10)
                .subscribe(i -> log.info("just int->" + i));
    }

    /***演示 from的基本使用  */
    @Test
    public void fromDemo() {
        //逐一发送一个数组中的每一个元素
        String[] items = {"a", "b", "c", "d", "e", "f"};
        Observable.fromArray(items)
                .subscribe(s -> log.info("just string->" + s));

        //逐一发送迭代器中的每一个元素
        Integer[] array = {1, 2, 3, 4};
        List<Integer> list = Arrays.asList(array);
        Observable.fromIterable(list)
                .subscribe(i -> log.info("just int->" + i));
    }
    /**
     *演示just的基本使用
     */
    @Test
    public void justDemo() {
        //发送一个字符串"hello world"
        Observable.just("hello world")
                .subscribe(s -> log.info("just string->" + s));
        //逐一发送1,2,3,4四个整数
        Observable.just(1, 2, 3, 4)
                .subscribe(i -> log.info("just int->" + i));
    }



}